import React, { FC } from 'react';
import { FormPanel, InputType, type FormPanelObject, FormPanelBtnAlign, StandUploadExcel, Utils } from 'lfun-bg-comp';
import { Breadcrumb, Button, Table, TableProps, Space, Modal, message, Flex } from 'antd';
import _ from 'lodash';
import { useLocation, useNavigate } from 'react-router-dom';
import CloseReson from '../../component/closeReson';
import Create from './create';
import { PageContainer } from '@/component/page-container';
import { KG_ORDER_STATUS, KG_LEVEL, FOUNDER_TYPE, SCHOOL_OPERATION_TYPE } from '@/constant/schoolOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import utils, { buildPageItemTxtByEduType, getPagePath, getPathRoot, get_stoge_pz, set_stoge_pz } from '@/utils';
//import ImportExcel from '@/component/importExcel';
import styles from './index.less';
import {
  CloseSchool,
  SearchSchool,
  closeSchool,
  deleteSchool,
  importSchool,
  searchSchool,
  getSchool,
} from '@/service/unit/school';
import { IMPORT_EXCEL_TEMPLATE } from '@/constant';
import useGetUrlParams from '@/hooks/useGetUrlParmas';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';

// eslint-disable-next-line react/require-default-props
const Groups: FC<{ isReadOnly?: boolean }> = ({ isReadOnly = true }) => {
  const [current, setCurrent] = React.useState();
  const [dataSource, setDataSource] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState(null);
  const [showCloseResone, setShowCloseResone] = React.useState(false);
  const [showCreateKG, setShowCreateKG] = React.useState(false);
  //const [showImportModel, setShowImporttModel] = React.useState(false);
  const [tableLoading, setTableLoading] = React.useState(false);
  const [planningSchoolId, setPlanningSchoolId] = React.useState();
  const getUrlParams = useGetUrlParams();
  const country = useCountry();
  const location = useLocation();

  const navigate = useNavigate();
  const isSchool = isReadOnly;
  const list: FormPanelObject[] = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      inputs: [
        {
          label: buildPageItemTxtByEduType('园所名称'),
          name: 'school_name',
          key: 'school_name',
          textRange: [0, 20],
        },
        {
          label: '举办者类型',
          name: 'founder_type',
          key: 'founder_type',
          inputType: InputType.cascader,
          inputProps: {
            multiple: true,
          },
          renderOption: FOUNDER_TYPE,
        },
        {
          label: '行政管辖区',
          name: 'borough',
          key: 'borough',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '地域管辖区',
          name: 'block',
          key: 'block',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '状态',
          name: 'status',
          key: 'status',
          inputType: InputType.select,
          renderOption: KG_ORDER_STATUS,
        },
        {
          label: buildPageItemTxtByEduType('机构编码'),
          name: 'school_code',
          key: 'school_code',
          textRange: [0, 20],
        },
        {
          label: '星级',
          name: 'school_level',
          key: 'school_level',
          inputType: InputType.select,
          renderOption: KG_LEVEL,
          hidden: Utils.getProps('edu_type') !== 'kg',
        },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '编号',
      width: 100,
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      fixed: 'left',
      render(val, row, index) {
        return index + 1;
      },
    },
    {
      title: buildPageItemTxtByEduType('机构编码'),
      width: 100,
      dataIndex: 'school_no',
      key: 'school_no',
      align: 'center',
      fixed: 'left',
    },
    {
      title: buildPageItemTxtByEduType(`园所名称(分${Utils.getProps('edu_type') === 'kg' ? '园' : '校'})`),
      width: 500,
      dataIndex: 'school_name',
      key: 'school_name',
      align: 'center',
      fixed: 'left',
    },
    {
      title: '行政管辖区',
      width: 150,
      dataIndex: 'borough',
      key: 'borough',
      align: 'center',
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    {
      title: '地域管辖区',
      width: 150,
      dataIndex: 'block',
      key: 'block',
      align: 'center',
      render: (text: any) => {
        return _.find(country, { value: String(text) })?.label;
      },
    },
    {
      title: '举办者类型',
      width: 300,
      dataIndex: 'founder_type',
      key: 'founder_type',
      align: 'center',
      render: (text: any) => {
        let arr: any[] = [];
        if (_.isArray(text)) {
          arr = text.map(v => utils.findLabelDeep(FOUNDER_TYPE, String(v)));
        }
        return arr.join('-');
      },
    },
    {
      title: buildPageItemTxtByEduType('园所星级'),
      width: 100,
      dataIndex: 'school_level',
      key: 'school_level',
      align: 'center',
      render: (text: any) => {
        return _.find(KG_LEVEL, { value: String(text) })?.label;
      },
    },
    // {
    //   title: '办学类型',
    //   width: 100,
    //   dataIndex: 'school_operation_type',
    //   key: 'school_operation_type',
    //   align: 'center',
    //   render: (text: any) => {
    //     let arr: any[] = [];
    //     if (_.isArray(text)) {
    //       arr = text.map(v => utils.findLabelDeep(SCHOOL_OPERATION_TYPE, String(v)));
    //     }
    //     return arr.join('-');
    //   },
    // },
    {
      title: '教育层次',
      dataIndex: 'school_edu_level',
      key: 'school_edu_level',
      align: 'center',
      width: 100,
      render: (text: any) => {
        return _.find(SCHOOL_OPERATION_TYPE, { value: String(text) })?.label;
      },
    },
    {
      title: '学校（机构）类别',
      dataIndex: 'school_category',
      key: 'school_category',
      align: 'center',
      width: 200,
      render: (text: any, record: any) => {
        const res = _.find(SCHOOL_OPERATION_TYPE, { value: record.school_edu_level });
        if (res) {
          return _.find(res.children, { value: String(text) })?.label;
        }
        return text;
      },
    },
    {
      title: '办学类型',
      dataIndex: 'school_operation_type',
      key: 'school_operation_type',
      width: 100,
      align: 'center',
      render: (text: any, record: any) => {
        const edu_level_res = _.find(SCHOOL_OPERATION_TYPE, { value: record.school_edu_level });
        if (edu_level_res) {
          const res = _.find(edu_level_res.children, { value: String(record.school_category) });
          if (res) {
            return _.find(res.children, { value: String(text) })?.label;
          }
        }
        return text;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      key: 'status',
      align: 'center',
      render: (text: any) => {
        return _.find(KG_ORDER_STATUS, { value: text })?.label;
      },
    },
    {
      title: '操作',
      dataIndex: 'op',
      key: 'op',
      fixed: 'right',
      //width: 200,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => {
        return (
          <Space>
            {!isSchool || (isSchool && !['draft'].includes(record.status)) ? (
              <PermissionButton permission="view">
                <Button
                  key="look"
                  type="link"
                  size="small"
                  onClick={() => {
                    // if (location.pathname === '/city/unit/k12/org') {
                    //   return navigate(`${getPathRoot()}/org/details/${record.id}`, { state: { ...record } });
                    // }

                    // return navigate(`${getPathRoot()}/class/details/${record.id}`, { state: { ...record } });
                    return navigate(`${getPathRoot()}/org/details/${record.id}`, { state: { ...record } });
                  }}
                >
                  查看
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {isSchool && ['draft'].includes(record.status) && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="edit">
                <Button
                  key="edit"
                  type="link"
                  size="small"
                  onClick={() => navigate(`${getPathRoot()}/school/edit/${record.id}`, { state: { ...record } })}
                >
                  编辑
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {isSchool &&
            ['normal'].includes(record.status) &&
            record.workflow_status !== 'needaudit' &&
            !Utils.getProps('isCity') &&
            !Utils.getProps('isCounty') ? (
              <PermissionButton permission="change">
                <Button
                  key="change"
                  type="link"
                  size="small"
                  onClick={() => {
                    navigate(`${getPathRoot()}/school/change/${record.id}`, { state: { ...record } });
                  }}
                >
                  变更
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {/* {isSchool && ['draft', 'opening'].includes(record.status) && record.workflow_status !== 'needaudit' ? (
              <Button
                key="opening"
                type="link"
                size="small"
                onClick={() => navigate(`${getPathRoot()}/school/edit/${record.id}`, { state: { ...record } })}
              >
                正式开办
              </Button>
            ) : (
              ''
            )} */}
            {isSchool && record.status === 'normal' && record.workflow_status !== 'needaudit' ? (
              <PermissionButton permission="close">
                <Button
                  key="close"
                  type="link"
                  size="small"
                  onClick={() => {
                    setShowCloseResone(true);
                    setCurrent(record.id);
                  }}
                >
                  关闭
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
            {isSchool &&
            record.status === 'draft' &&
            record.workflow_status !== 'needaudit' &&
            !Utils.getProps('isCity') &&
            !Utils.getProps('isCounty') ? (
              <PermissionButton permission="delete">
                <Button
                  type="link"
                  size="small"
                  onClick={() => {
                    Modal.confirm({
                      title: '删除',
                      content: `确定否删除‘${record.school_name}’的相关信息`,
                      onOk: async () => {
                        const r = await deleteSchool(record.id);
                        if (r?.success) {
                          message.success('删除成功');
                          search(form?.getFieldsValue(), pageSize, pageIndex);
                        } else {
                          throw new Error();
                        }
                      },
                    });
                  }}
                >
                  删除
                </Button>
              </PermissionButton>
            ) : (
              ''
            )}
          </Space>
        );
      },
    },
  ];
  const buildBtns = () => {
    return [
      <PermissionButton permission="export">
        <Button type="primary" key="export">
          导出
        </Button>
      </PermissionButton>,
    ];
  };

  const search = async (params: any, pageSize, pageIndex) => {
    if (tableLoading) {
      return;
    }
    setTableLoading(true);
    const searchParams: SearchSchool = {
      ...params,
      planning_school_id: getUrlParams.query.get('planning_school_id'),
    };
    if (params && params.founder_type && params.founder_type.length > 0) {
      const fouder_type_set1 = new Set<string>();
      const fouder_type_set2 = new Set<string>();
      const fouder_type_set3 = new Set<string>();
      params.founder_type.forEach(item => {
        if (item.length > 2) fouder_type_set3.add(item[2]);
        else if (item.length > 1) fouder_type_set2.add(item[1]);
        else if (item.length > 0) fouder_type_set1.add(item[0]);
      });
      searchParams.founder_type = Array.from(fouder_type_set1);
      searchParams.founder_type_lv2 = Array.from(fouder_type_set2);
      searchParams.founder_type_lv3 = Array.from(fouder_type_set3);
    }
    const { success, data } = await searchSchool(searchParams, pageIndex, pageSize);
    if (success) {
      setDataSource(
        data?.items?.map((v, i) => {
          v.key = i;
          v.founder_type = [v.founder_type, v.founder_type_lv2, v.founder_type_lv3];
          v.planning_school_operation_type = [
            v.planning_school_operation_type,
            v.planning_school_operation_type_lv2,
            v.planning_school_operation_type_lv3,
          ];
          return v;
        })
      );
      setTotal(data.total);
      setPageSize(pageSize);
      setPageIndex(pageIndex);
      setTableLoading(false);
    }
  };

  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize);
    search(form?.getFieldsValue(), pageSize, pageIndex);
  };

  const _get_planning_school_id = async () => {
    getSchool(Utils.getProps('schoolInfo')?.school_id)
      .then(res => {
        setPlanningSchoolId(res.data?.school_keyinfo?.planning_school_id);
      })
      .catch(err => {
        console.log(err);
      });
  };

  React.useEffect(() => {
    search({}, pageSize, 1);
    _get_planning_school_id();
    //return () => {};
  }, []);

  return (
    <PageContainer header={<Breadcrumb items={[{ title: getPagePath().power_name }]} />}>
      <FormPanel
        template={list}
        key={1}
        submitBtnText="搜索"
        restBtnText="重置"
        btnsAlign={FormPanelBtnAlign.right}
        buttons={isSchool ? buildBtns() : []}
        onFinish={(formPanelObject: FormPanelObject) => {
          const params = formPanelObject.getFieldsValue();
          search(params, pageSize, 1);
          setForm(form);
          return false;
        }}
      />
      {isSchool && (
        <Flex gap="small" wrap="wrap" style={{ marginBottom: 20 }}>
          <PermissionButton permission="import">
            <StandUploadExcel
              uploadSrv="/school/v1/storage/school-upload-uri"
              templateUrl={IMPORT_EXCEL_TEMPLATE.school}
              templateName="资源导入模版.xlsx"
              showExcelSrv="/school/v1/storage/file-data-preview"
              scene="school"
              onImport={async (data, file_name, bucket_name) => {
                const res = await importSchool({
                  file_name,
                  bucket_name,
                  scene: 'school',
                });
                if (res.success) {
                  message.success('导入成功');
                  search({}, pageSize, 1);
                } else {
                  message.error(res.message || res.details);
                }
                return res.success;

              }}
            >
              导入
            </StandUploadExcel>
          </PermissionButton>
          {!Utils.getProps('isCity') && (
            <PermissionButton permission="open">
              <Button key="openkg" type="primary" onClick={() => setShowCreateKG(true)}>
                {buildPageItemTxtByEduType('开办园所')}
              </Button>
            </PermissionButton>
          )}
        </Flex>
      )}

      <Table
        loading={tableLoading}
        className={styles.table}
        dataSource={dataSource.map((v, idx) => {
          v.key = idx;
          return v;
        })}
        scroll={{ x: 'max-content' }}
        columns={Utils.getProps('edu_type') === 'kg' ? columns : columns.filter(it => it.key !== 'school_level')}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <CloseReson
        show={showCloseResone}
        onCancel={form => {
          form.resetFields();
          setShowCloseResone(false);
        }}
        onOk={async (formPanelObject: FormPanelObject) => {
          const values = formPanelObject.getFieldsValue();
          const closeParams: CloseSchool = {
            school_id: current,
            ...values,
          };
          const res = await closeSchool(closeParams);
          if (res.success) {
            message.success('关闭成功');
            setShowCloseResone(false);
            search(form?.getFieldsValue(), pageSize, pageIndex);
            form.resetFields();
          } else {
            formPanelObject.reVaildation(res);
          }
        }}
      />
      <Create
        show={showCreateKG}
        planningSchoolId={planningSchoolId}
        onCancel={() => setShowCreateKG(false)}
        // onOk={(form, values) => {
        //   console.log(form, values);
        // }}
      />
      {/* <ImportExcel
        templateUrl="https://minio.f123.pub/demo-private/9886560931.xlsx"
        getExcelSrv="/getExcel"
        show={showImportModel}
        onImport={data => {
          console.log(data);
        }}
        onCancel={() => setShowImporttModel(false)}
      /> */}
    </PageContainer>
  );
};

export default Groups;
